﻿#region Using directives
using System;
using System.Web.UI;
using ProcolDemo.IdeasReference;
using ProcolDemo.IdeaUpdates;
using System.Web.UI.WebControls;
using ProcolDemo.User;

#endregion

namespace ProcolDemo {
    public partial class Ideas : Page {
        protected void Page_Load(object sender, EventArgs e) {

            if (!Page.IsPostBack)
            {
                if (!Common.IsUserLoggedIn(Session))
                    Response.Redirect("Default.aspx");
                Common.FillI18NStrings(this, Session);

                /* VARIABLES INITIALIZATION */
                IdeasService ideasService = new IdeasService();
                UserService userService = new UserService();
                int userId = Common.GetUserId(Session);
                int userRole = userService.GetUserRole(userId);
                userRoleField.Value = userRole + "";
                String op = Request.QueryString["op"];
                if (op == null) op = "";

                /* INITIALLY HIDDEN SECTIONS */
                results.Visible = false;
                ideaInfo.Visible = false;
                editIdea.Visible = false;
                displayComments.Visible = false;
                searchForTag.Visible = false;

                /* POPULATE TAGS SIDEBAR */
                IdeaTagBean[] projectTags = ideasService.getIdeaTags();
                IdeasTagsSidebar.DataSource = projectTags;
                IdeasTagsSidebar.DataBind();

                /* DISPLAY IDEA'S INFORMATION */
                if (op.Equals("ideaInfo"))
                {
                    int ideaId;
                    if (!Int32.TryParse(Request.QueryString["ideaId"], out ideaId))
                        ideaId = 0;
                    ideaInfo.Visible = true;
                    displayComments.Visible = true;
                    results.Visible = false;
                    searchIdea.Visible = false;
                    newIdea.Visible = false;
                    myIdeas.Visible = false;
                    star1.Visible = false;
                    star2.Visible = false;
                    star3.Visible = false;
                    star4.Visible = false;
                    star5.Visible = false;
                    IdeaBean idea = ideasService.GetIdea(ideaId);
                    ideaIdValueComment.Value = idea.ideaId.ToString();
                    displayIdea_ideaName.Text = idea.name;
                    displayIdea_ideaCategory.Text = idea.category;
                    displayIdea_ideaOwner.Text = idea.ownersName;
                    userProfileLink.NavigateUrl = "ViewProfile.aspx?Uid=" + idea.userId;
                    userProfileLink2.NavigateUrl = "ViewProfile.aspx?Uid=" + idea.tutorId;
                    displayIdea_ideaCreationDate.Text = idea.dateCreated.Day + "/" +
                            idea.dateCreated.Month + "/" + idea.dateCreated.Year;
                    displayIdea_ideaTags.Text = idea.tags;
                    displayIdea_ideaDescription.Text = idea.description;
                    displayIdea_tutorName.Text = userService.GetUserName(idea.tutorId);
                    if (idea.rating >= 1) star1.Visible = true;
                    if (idea.rating >= 2) star2.Visible = true;
                    if (idea.rating >= 3) star3.Visible = true;
                    if (idea.rating >= 4) star4.Visible = true;
                    if (idea.rating >= 5) star5.Visible = true;
                    if (ideasService.isOwner(userId, ideaId)) isOwner.Value = "true";
                    editIdeaLink.NavigateUrl = "Ideas.aspx?op=editIdea&ideaId=" + ideaId;
                    IdeaCommentBean[] commentsList = ideasService.GetListOfIdeasComments(ideaId);
                    if (commentsList.Length == 0)
                        noComments.InnerHtml = "<center>There are no comments.</center><br /> <br />";
                    else
                    {
                        displayIdeasComments.DataSource = commentsList;
                        displayIdeasComments.DataBind();
                    }

                    subscribeLink.HRef = String.Format("http://localhost:1059/RssGenerator.aspx?type=ideas&Uid={0}&id={1}", userId, ideaId);
                    /* EDIT IDEA'S INFORMATION */
                }
                else if (op.Equals("editIdea"))
                {
                    int ideaId;
                    if (!Int32.TryParse(Request.QueryString["ideaId"], out ideaId))
                        ideaId = 0;
                    editIdea.Visible = true;
                    results.Visible = false;
                    searchIdea.Visible = false;
                    newIdea.Visible = false;
                    myIdeas.Visible = false;
                    IdeaBean idea = ideasService.GetIdea(ideaId);
                    ideaIdValue.Value = idea.ideaId.ToString();
                    editIdea_ideaName.Text = idea.name.TrimEnd();
                    editIdea_ideaCategory.Text = idea.category.TrimEnd();
                    editIdea_ideaDescription.Text = idea.description.TrimEnd();
                    if (idea.tags != null)
                        editIdea_ideaTags.Text = idea.tags.TrimEnd();
                    int[] tutors = userService.GetListOfTeachers();
                    for (int i = 0; i < tutors.Length; i++)
                    {
                        editIdeaTutorId.Items.Add(new ListItem(userService.GetUserName(tutors[i]), tutors[i] + ""));
                    }
                }

                /* SEARCH FOR TAG */
                else if (op.Equals("tag"))
                {
                    int idTag;
                    if (!Int32.TryParse(Request.QueryString["idTag"], out idTag))
                        idTag = 0;
                    searchForTag.Visible = true;
                    ideaInfo.Visible = false;
                    displayComments.Visible = false;
                    results.Visible = false;
                    searchIdea.Visible = false;
                    myIdeas.Visible = false;
                    newIdea.Visible = false;
                    IdeaBean[] projectsWithTag = ideasService.searchForTag(idTag);
                    searchForTagTable.DataSource = projectsWithTag;
                    searchForTagTable.DataBind();
                    searchForTag_TagName.Text = ideasService.getTagName(idTag);
                }

                /* POPULATE LIST OF POSSIBLE TUTORS */
                int[] tutorsList = userService.GetListOfTeachers();
                for (int i = 0; i < tutorsList.Length; i++)
                {
                    tutorIdList.Items.Add(new ListItem(userService.GetUserName(tutorsList[i]), tutorsList[i] + ""));
                }

                /* DISPLAY MY IDEAS */
                IdeaBean[] ideasList = ideasService.GetListOfIdeasByUserId(Common.GetUserId(Session));
                for (int i = 0; i < ideasList.Length; i++)
                    if (ideasList[i].nameLength > 65)
                        ideasList[i].name = ideasList[i].name.Substring(0, 64) + "...";
                ShowMyIdeas.DataSource = ideasList;
                ShowMyIdeas.DataBind();

                /* SET MAXIMUM RESULTS FOR AUTOCOMPLETE SEARCH FIELD */
                txtSearch_AutoCompleteExtender.CompletionSetCount = 10;
            }
        }

        /* SIMPLE SEARCH BUTTON */
        protected void SimpleSearch_Click(object sender, EventArgs e)
        {
            IdeasService ideasService = new IdeasService();

            //if (String.IsNullOrEmpty(txtSearch.Text))
            results.Visible = true;
            searchIdea.Visible = true;
            newIdea.Visible = false;
            myIdeas.Visible = false;
            
            IdeaBean[] ideasList = ideasService.GetListOfIdeasByKeyword(txtSearch.Text);
            for (int i = 0; i < ideasList.Length; i++)
                if (ideasList[i].nameLength > 75)
                    ideasList[i].name = ideasList[i].name.Substring(0, 74) + "...";

            ShowResults.DataSource = ideasList;
            ShowResults.DataBind();
        }

        protected void txtSearch_TextChanged(object sender, EventArgs e)
        {
        }

        /* UPLOAD FILE */
        protected void ButtonFileUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload.HasFile)
                try
                {
                    FileUpload.SaveAs("C:\\MEDIA\\Mexico\\Studium\\AdvancedInternet\\Project\\LastVersion\\ProcolDemo\\UploadFiles\\" +
                         FileUpload.FileName);
                    lblFileUpload.Text = "File name: " +
                         FileUpload.PostedFile.FileName + "<br>" +
                         FileUpload.PostedFile.ContentLength + " kb<br>" +
                         "Content type: " +
                         FileUpload.PostedFile.ContentType;
                }
                catch (Exception ex)
                {
                    lblFileUpload.Text = "ERROR: " + ex.Message.ToString();
                }
            else
            {
                lblFileUpload.Text = "You have not specified a file.";
            }
        }

        protected void Button1_Click(object sender, EventArgs e) {
            IdeasService ideaService = new IdeasService();
            byte status = 1;
            int ideaId = ideaService.AddNewIdea(Common.GetUserId(Session), newIdea_ideaDescription.Text, status, DateTime.Now, newIdea_ideaName.Text, newIdea_ideaCategory.Text, newIdea_ideaTags.Text, Int32.Parse(tutorIdList.SelectedItem.Value.ToString()));
            UserService userService = new UserService();
            String username = userService.GetUserName(Common.GetUserId(Session));
            IdeaUpdatesService createIdeaUpdate = new IdeaUpdatesService();
            createIdeaUpdate.AddIdeaUpdate("UPDATE_IDEA_NEWIDEA", ideaId, Common.GetUserId(Session), -1, DateTime.Now);
            IdeaBean[] ideasList = ideaService.GetListOfIdeasByUserId(Common.GetUserId(Session));
            for (int i = 0; i < ideasList.Length; i++)
                if (ideasList[i].nameLength > 65)
                    ideasList[i].name = ideasList[i].name.Substring(0, 64) + "...";
            ShowMyIdeas.DataSource = ideasList;
            ShowMyIdeas.DataBind();
            CollapsiblePanelExtender2.Collapsed = true;
            /**** Don´t erase or uncomment this lines *****/
            /*NewIdeaMessage.Visible = true;
            newIdeaMessPopUpExtender.Show();*/
        }

        public void deleteIdea_Click(object sender, CommandEventArgs e)
        {
            int ideaId = System.Convert.ToInt32(e.CommandArgument.ToString());
            IdeasService ideaService = new IdeasService();
            ideaService.LogicDeleteIdea(ideaId);
            IdeaUpdatesService createIdeaUpdate = new IdeaUpdatesService();
            createIdeaUpdate.AddIdeaUpdate("UPDATE_IDEA_DELETE", ideaId, Common.GetUserId(Session), -1, DateTime.Now);
            IdeaBean[] ideasList = ideaService.GetListOfIdeasByUserId(Common.GetUserId(Session));
            for (int i = 0; i < ideasList.Length; i++)
                if (ideasList[i].nameLength > 65)
                    ideasList[i].name = ideasList[i].name.Substring(0, 64) + "...";
            ShowMyIdeas.DataSource = ideasList;
            ShowMyIdeas.DataBind();
        }

        protected void editIdea_OKButton_Click(object sender, EventArgs e)
        {
            IdeasService ideaService = new IdeasService();
            UserService userService = new UserService();
            int ideasId = Int32.Parse(ideaIdValue.Value);
            ideaService.UpdateIdeaRecord(ideasId, editIdea_ideaDescription.Text, editIdea_ideaName.Text, editIdea_ideaCategory.Text, editIdea_ideaTags.Text, Int32.Parse(tutorIdList.SelectedItem.Value.ToString()));
            IdeaUpdatesService createIdeaUpdate = new IdeaUpdatesService();
            createIdeaUpdate.AddIdeaUpdate("UPDATE_IDEA_EDIT", ideasId, Common.GetUserId(Session), -1, DateTime.Now);
            IdeaBean[] ideasList = ideaService.GetListOfIdeasByUserId(Common.GetUserId(Session));
            for (int i = 0; i < ideasList.Length; i++)
                if (ideasList[i].nameLength > 65)
                    ideasList[i].name = ideasList[i].name.Substring(0, 64) + "...";
            ShowMyIdeas.DataSource = ideasList;
            ShowMyIdeas.DataBind();
            editIdea.Visible = false;
            results.Visible = false;
            searchIdea.Visible = true;
            newIdea.Visible = true;
            myIdeas.Visible = true;
        }

        protected void postComment_Button_Click(object sender, EventArgs e)
        {
            IdeasService ideaService = new IdeasService();
            int ideasId = Int32.Parse(ideaIdValueComment.Value);
            int ideaSubmit = ideaService.AddNewComment(Common.GetUserId(Session), ideasId, newCommentText.Text, newCommentTitle.Text);
            IdeaUpdatesService createIdeaUpdate = new IdeaUpdatesService();
            createIdeaUpdate.AddIdeaUpdate("UPDATE_IDEA_NEWCOMMENT", ideasId, Common.GetUserId(Session), -1, DateTime.Now);

            if ((ideaSubmit != -1) || (ideaSubmit != -2)) {
                IdeaCommentBean[] commentsList = ideaService.GetListOfIdeasComments(ideasId);
                displayIdeasComments.DataSource = commentsList;
                displayIdeasComments.DataBind();
            }
            newCommentText.Text = "";
            newCommentTitle.Text = "";
            /*ideaInfo.Visible = false;
            displayComments.Visible = false;
            editIdea.Visible = false;
            results.Visible = false;
            searchIdea.Visible = true;
            newIdea.Visible = true;
            myIdeas.Visible = true;*/
        }

        
    }
}
